#include "netcli.hpp"
#include <arpa/inet.h>
#include <cstring>
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

netcli::netcli(char* ip, int port)
{
    int ret = 0;

    strcpy(ser_ip, ip);
    ser_port = port;

    cli_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (cli_fd < 0) {
        std::cerr << "Could not create socket" << std::endl;
    }
}

netcli::~netcli()
{
    close(cli_fd);
}

int netcli::send(char* buf, int len)
{
    int ret = 0;
    struct sockaddr_in ser_addr;

    memset(&ser_addr, 0, sizeof(struct sockaddr_in));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(ser_port);
    ret = inet_pton(AF_INET, ser_ip, &ser_addr.sin_addr);
    if (ret < 0) {
        std::cerr << "Invalid address/ Address not supported" << std::endl;
        return -1;
    }

    ret = sendto(cli_fd, (const char*)buf, len, MSG_CONFIRM, (const struct sockaddr*)&ser_addr, sizeof(ser_addr));
    if (ret < 0) {
        std::cerr << "Send failed" << std::endl;
        return -1;
    }

    return 0;
}

int netcli::recv(char* buf, int size)
{
    int ret = 0;
    socklen_t len = 0;
    struct sockaddr_in ser_addr;

    len = sizeof(struct sockaddr_in);
    ret = recvfrom(cli_fd, (char*)buf, size, MSG_WAITALL, (struct sockaddr*)&ser_addr, &len);
    if (ret < 0) {
        std::cerr << "Receive failed" << std::endl;
        return 1;
    }

    return 0;
}
